//
//  Rx+TargetType.swift
//  XNetwork_Example
//
//  Created by x on 2024/8/9.
//  Copyright © 2024 CocoaPods. All rights reserved.
//


import RxSwift
import Moya

public extension TargetType {
    func requset(callbackQueue: DispatchQueue? = nil) ->Single<Moya.Response> {
        let actualRequest = Network.default.provider.rx.request(.target(self), callbackQueue: callbackQueue) as Single<Response>
        let config = Network.default.config
        return config.online
            .exclude(value: false)
            .take(1).asSingle()
            .flatMap { _ in return
                actualRequest
                    .filterSuccessfulStatusCodes()
                    .do(onSuccess: { (response) in}, onError: {(error) in
                        if let error = error as? MoyaError {
                            switch error {
                            case .statusCode(let response):
                                switch response.statusCode {
                                case 500:
                                    throw NetworkError.responseException(.serverException)
                                case 404:
                                    throw NetworkError.responseException(.notFound)
                                default:
                                    NetworkError.responseException(.unacceptableStatusCode(code: response.statusCode, response: response))
                                }
                            case .underlying(let error, _):
                                throw NetworkError.requestException(.networkException(error))
                            default:
                                throw NetworkError.responseSerializationException(.jsonSerializationFailed(nil))
                            }
                        }
                    })
            }
    }
}
